<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学期" prop="semId">
        <el-select v-model="queryParams.semId" filterable clearable placeholder="请选择学期">
          <el-option
            v-for="item in semsterList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="实验室" prop="labId">
        <el-select v-model="queryParams.labId" filterable clearable placeholder="请输入实验室">
          <el-option
            v-for="item in labList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="申请人" prop="teacherId">
         <el-select v-model="queryParams.teacherId" placeholder="请输入教师姓名" clearable filterable>
           <el-option
             v-for="dict in teacherList"
             :key="dict.userId"
             :label="dict.name"
             :value="dict.userId"
           />
         </el-select>
      </el-form-item>
      <el-form-item label="使用时间" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
      </el-form-item>
      <el-form-item label="审核状态" prop="checkStatus">
        <el-select v-model="queryParams.checkStatus" placeholder="请选择审核状态" clearable size="small">
          <el-option
            v-for="dict in checkStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lab:labApply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleCheck1"
          v-hasPermi="['lab:labApply:check']"
        >审核通过</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleCheck2"
          v-hasPermi="['lab:labApply:check']"
        >审核不通过</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['lab:labApply:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lab:labApply:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="labApplyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="实验室" align="center" prop="labName" />
      <el-table-column label="学期" align="center" prop="semName" />
      <el-table-column label="申请教师工号" align="center" prop="code" />
      <el-table-column label="申请教师姓名" align="center" prop="name" />
      <el-table-column label="开始使用时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束使用时间" align="center" prop="finishTimes" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.finishTimes, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用时长" align="center" prop="timeLong" />
      <el-table-column label="使用学生数" align="center" prop="students" />
      <el-table-column label="审核状态" align="center" prop="checkStatus" :formatter="checkStatusFormat" />
      <el-table-column label="附件资料" align="center" prop="fileId">
        <template slot-scope="scope">
          <span v-html="getDownLink(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-help"
            @click="handleView(scope.row)"
            v-hasPermi="['lab:labApply:edit']"
          >详细</el-button>
          <el-button v-if="scope.row.checkStatus != '1'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lab:labApply:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改实验室申请对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
       <el-tabs type="card" >
        <el-tab-pane label="基本信息">
        <el-form-item label="学期" prop="semId">
          <el-select v-model="form.semId" filterable :disabled="this.form.views" clearable placeholder="请选择学期">
            <el-option
              v-for="item in semsterList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验室" prop="labId">
          <el-select v-model="form.labId" filterable :disabled="this.form.views" clearable placeholder="请输入实验室">
            <el-option
              v-for="item in labList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请人" prop="teacherId">
         <el-select v-model="form.teacherId" placeholder="请输入教师姓名" :disabled="this.form.views" clearable filterable>
           <el-option
             v-for="dict in teacherList"
             :key="dict.userId"
             :label="dict.name"
             :value="dict.userId"
           />
         </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable size="small" style="width: 200px" :disabled="this.form.views"
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始使用时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="finishTimes">
          <el-date-picker clearable size="small" style="width: 200px" :disabled="this.form.views"
            v-model="form.finishTimes"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束使用时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="使用时长" prop="timeLong">
          <el-input v-model="form.timeLong" placeholder="请输入使用时长(分钟)" :disabled="this.form.views"/>
        </el-form-item>
        <el-form-item label="学生数" prop="students">
          <el-input v-model="form.students" placeholder="请输入使用学生数" :disabled="this.form.views"/>
        </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="详细说明">
        <el-form-item label="申请说明" prop="comment">
          <el-input v-model="form.comment" type="textarea" placeholder="请输入申请说明" :disabled="this.form.views"/>
        </el-form-item>
        <el-form-item label="附件资料" prop="fileId">
            <span v-html="getDownLink(form)" v-if="form.file != null"></span>
        </el-form-item>
        </el-tab-pane>
      </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!this.form.views">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的课堂考勤数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLabApply, getLabApply, delLabApply, checkLabApply, addLabApply, updateLabApply, exportLabApply, importTemplate } from "@/api/lab/labApply";
import { selectLaboratory} from "@/api/lab/laboratory";
import { getToken } from "@/utils/auth";
import { selectSemster} from "@/api/base/semster";
import { listTeacher} from "@/api/base/teacher";

export default {
  name: "LabApply",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教师数据
      teacherList: [],
      // 实验室数据
      labList: [],
      // 学期数据
      semsterList: [],
      // 实验室申请表格数据
      labApplyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 审核状态字典
      checkStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        labId: null,
        semId: null,
        teacherId: null,
        startTime: null,
        finishTime: null,
        addUser: null,
        addTime: null,
        checkStatus: null,
      },
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/lab/labApply/importData"
      },
      // 表单校验
      rules: {
        labId: [
          { required: true, message: "实验室不能为空", trigger: "blur" }
        ],
        semId: [
          { required: true, message: "学期不能为空", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "申请人不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始使用时间不能为空", trigger: "blur" }
        ],
        finishTimes: [
          { required: true, message: "结束使用时间不能为空", trigger: "blur" }
        ],
        timeLong: [
          { required: true, message: "使用时长不能为空", trigger: "blur" }
        ],
        students: [
          { required: true, message: "使用学生数不能为空", trigger: "blur" }
        ],
        addUser: [
          { required: true, message: "记录人不能为空", trigger: "blur" }
        ],
        addTime: [
          { required: true, message: "记录时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("check_status").then(response => {
      this.checkStatusOptions = response.data;
    });
    selectSemster({'status':1}).then(response => {
      this.semsterList = response.rows;
    });
    selectLaboratory().then(response => {
      this.labList = response.rows;
    });
    listTeacher().then(response => {
      this.teacherList = response.rows;
      this.total = response.total;
      this.loading = false;
    });
  },
  methods: {
    /** 查询实验室申请列表 */
    getList() {
      this.loading = true;
      listLabApply(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.labApplyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 审核状态字典翻译
    checkStatusFormat(row, column) {
      return this.selectDictLabel(this.checkStatusOptions, row.checkStatus);
    },
    /** 下载附件链接 */
    getDownLink(row) {
      if(row.file && row.file.id){
        return '<a href="'+process.env.VUE_APP_BASE_API+'/sys/files/download/'+row.file.id+'" target="_blank">'+row.file.title+'</a>';
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        labId: null,
        semId: null,
        teacherId: null,
        startTime: null,
        finishTime: null,
        timeLong: null,
        students: null,
        addUser: null,
        addTime: null,
        updateUser: null,
        updateTime: null,
        checkStatus: "0",
        comment: null,
        fileId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实验室申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLabApply(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改实验室申请";
      });
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getLabApply(id).then(response => {
        this.form = response.data;
        this.form.views = true;
        this.open = true;
        this.title = "查看实验室申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLabApply(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLabApply(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除实验室申请编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLabApply(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 审核通过按钮操作 */
    handleCheck1 (row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认将选中的申请信息设置为 审核通过 状态吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return checkLabApply({batchs:ids, checkStatus: '1'});
        }).then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        })
    },
    /** 审核不通过按钮操作 */
    handleCheck2 (row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认将选中的申请信息设置为 审核不通过 状态吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return checkLabApply({batchs:ids, checkStatus: '2'});
        }).then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有实验室申请数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportLabApply(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "实验室申请导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
